#!/usr/bin/python

import sys,string
import hashlib 
from socket import *
server_host_port=[
        ["127.0.0.1",12324],
        ["127.0.0.1",12322],
        ["127.0.0.1",12325]
        ]

sock_con_fd=[]

def store_item(key,flags,exptime,length,data):
    host_index = get_host_index(key)
    now_host_hostname = server_host_port[host_index][0]
    now_host_port = server_host_port[host_index][1]
    print now_host_hostname 
    print now_host_port
    # connect to server on the port
    request = "set %s %s %s %s %s" % (key,flags,exptime,length,data)
    #request ='set ' + key + ' ' + flags + ' '+ exptime + '' + length + '' + data
    print request
    sock_con_fd[host_index][0].send(request)
    reply = sock_con_fd[host_index][0].recv(1024)                 # receive up to 1K bytes
    print reply

def get_item(key):
    host_index = get_host_index(key)
    now_host_hostname = server_host_port[host_index][0]
    now_host_port = server_host_port[host_index][1]
    print now_host_hostname 
    print now_host_port
    # connect to server on the port
    request ='get %s' % (key)
    sock_con_fd[host_index][0].send(request)
    reply = sock_con_fd[host_index][0].recv(1024)
    print reply

def get_host_index(key):
    host_index = int(hashlib.md5(key).hexdigest(),16) % len(server_host_port)
    print host_index
    return host_index

def connect_host():
    for host_index in range(len(server_host_port)):
        sock_con_fd.append([])
        sock_fd = socket(AF_INET, SOCK_STREAM)
        print sock_fd
        conn_fd = sock_fd.connect((server_host_port[host_index][0],server_host_port[host_index][1]))
        print conn_fd
        sock_con_fd[host_index].insert(0,sock_fd)
        sock_con_fd[host_index].insert(1,conn_fd)
    for item in sock_con_fd:
        print item

def close_connection():
    for host_index in range(len(server_host_port)):
        sock_con_fd[host_index][0].close()

#if __name__=="__main__":
#    print("now in main")
#    connect_host()
#    for j in range(1,1000):
#        key = string.join(random.sample(['z','y','x','w','v','u','t','s','r','a'], 5)).replace(' ','') 
#        print(key)
#        store_item(key)
#    close_connection()
